import { getCoupList, getCoupDetail } from '../api/coup'
import { delCoup, checkPromotionProductList, createCoup } from '../api/coupContent'
import { generateRandomString } from '../utils/tools'
import moment from 'moment'
import {
    getLocStopConfigFun, setRunStatusFun,
    // setGetIndex 
} from '../methodAPI/index'

export const getCoupListFun = async (config, cb) => {
    // const getDeteliList = localStorage.getItem('couplistDatas')
    chrome.storage.local.get(['couplistDatas'], async function (result) {
        // console.log('result.initTiyangfenData', result.initTiyangfenData);
        // console.log('1213645', result['couplistDatas'])
        if (result['couplistDatas']) {
            const getDeteliList = result['couplistDatas']
            const { noCounpGoodList, getTime, goodsScope } = config

            let start_apply_time = getTime[0] // new Date().getTime()
            let end_apply_time = getTime[1] //new Date().getTime()
            config.end_apply_time = end_apply_time
            config.start_apply_time = start_apply_time >= new Date().getTime() / 1000 ? start_apply_time : new Date().getTime() / 1000
            if (config.end_apply_time <= (new Date().getTime() / 1000)) {
                setRunStatusFun(false)
                return cb && cb({
                    code: 0,
                    type: 'runEndTime',
                    config
                })
            }
            if (getDeteliList) {
                const getDeteliListJson = getDeteliList
                if (getDeteliListJson && getDeteliListJson.length) {
                    // console.log('第一个', getDeteliListJson)
                    await cheackGoodsComper(getDeteliListJson, config, cb)
                    return
                }
            }
            getDeteHettps(config, cb)
            try {

            } catch (error) {

            }
        } else {
            console.log('不存在，无法完成更新')
            getDeteHettps(config, cb)
        }
    });
    // console.log('config', config, getDeteliList)

}

let regetlistNum = 0
let repetNum = 5

async function getDeteHettps(config, cb) {
    // 单任务配置
    let dataList = []
    let getDetils = []
    const getListQurData = {
        coupon_type_group: 0,
        favoured_type: 0,
        status: 3,
        page: 1,
        size: 100,
        // start_apply_time: config.start_apply_time.toFixed(0) * 1,
        // end_apply_time: config.end_apply_time.toFixed(0) * 1
    }
    // 获取所有进行中生效的优惠券
    const getListAlls = await getDataConber(getListQurData)
    const getListQurData13 = {
        coupon_type_group: 0,
        favoured_type: 0,
        status: 13,
        page: 1,
        size: 100,
        // start_apply_time: config.start_apply_time.toFixed(0) * 1,
        // end_apply_time: config.end_apply_time.toFixed(0) * 1
    }
    const getListAlls13 = await getDataConber(getListQurData13)
    console.log('getListAlls13', getListAlls13)
    console.log('getListAlls', getListAlls)
    if (!getListAlls || !getListAlls13) {
        console.log('网络失败 解除 等待下次')
        regetlistNum = 0
        // setRunStatusFun(true)
        cb && cb({
            code: 0,
            type: 'runErroutime'
        })
        return
    }
    getListAlls.push(...getListAlls13)
    // console.log('getListAlls', getListAlls)
    // return
    getListAlls.forEach(item => {
        if (!item.getDeteil) {
            getDetils.push(item)
        }
    })
    console.log('getListAlls', getListAlls)
    getDetils = getListAlls.filter(item => !item.getDeteil)

    // 获取需要查看详情才能知道商品所在的优惠券的信息列表
    const getrdr = await getCoupDeteilCb(getDetils)
    // 到这里已经获取完全部的生效优惠券 以及生效的优惠券对应的商品
    console.log('getrdr0000+++++', getrdr)
    if (!getrdr) {
        console.log('网络失败 解除 等待下次')
        // setRunStatusFun(true)
        cb && cb({
            code: 0,
            type: 'runErroutime'
        })
        return
    }
    // 检查活动信息是否满足需要创建的配置条件
    // console.log('getListAlls123465', getListAlls)
    try {
        // localStorage.setItem('couplistDatas', JSON.stringify(getListAlls))
        chrome.storage.local.set({
            couplistDatas: getListAlls
        })

    } catch (error) {
        console.log('addERR', error)
    }
    console.log('第二个')
    await cheackGoodsComper(getListAlls, config, cb)








    return getListAlls

    // 获取所有进行中生效的优惠券
    async function getDataConber(data) {
        regetlistNum++
        if (regetlistNum >= repetNum) return false
        const getDataAwter = await getCoupList(data).catch(err => {
            console.log('getCoupListERR', err)
            return false
        })
        console.log('getDataAwter0000+++++', getDataAwter)
        if (!getDataAwter) {
            return getDataConber(data)
        }
        if (!getDataAwter.code) {
            regetlistNum = 0
            getDataAwter.data.forEach(items => {
                if (items.goods_count === 0) {
                    if (items.favoured_type > 40) {
                        items.getDeteil = false
                        items.goods_list = []
                        return
                    }
                    items.getDeteil = true
                    items.goods_list = []
                    return
                }
                if (items.goods_count === 1) {
                    // 只有一个商品 不需要请求
                    items.getDeteil = true
                    items.goods_list = [items.url.split('?id=')[1]]
                    return
                }
                items.getDeteil = false
                items.goods_list = []
            })
            dataList.push(...getDataAwter.data)
            if (data.page * data.size < getDataAwter?.total) {
                data.page++
                return getDataConber(data)
            } else {
                return dataList.filter(item => item.status === 3 || item.status === 13).map(res => {
                    return {
                        coupon_meta_id: res.coupon_meta_id,
                        goods_list: res.goods_list,
                        goods_count: res.goods_count,
                        start_apply_time: res.start_apply_time,
                        end_apply_time: res.end_apply_time,
                        total_amount: res.total_amount,
                        left_amount: res.left_amount,
                        used_amount: res.used_amount,
                        getDeteil: res.getDeteil
                    }
                })
            }
        }
    }

    async function getCoupDeteilCb(getDetilsDetr) {
        // 批量完成 // 做一个分组 防止报错
        const upDeteailContent = []
        while (getDetilsDetr.length) {
            const spliterConters = getDetilsDetr.splice(0, 10)
            upDeteailContent.push(spliterConters)
        }
        console.log('upDeteailContent', upDeteailContent)
        const getCoupDeteilAlls = await getCoupDeteailList(upDeteailContent)
        console.log('所有对', getCoupDeteilAlls)
        // console.log('getDetilsDetrgetDetilsDetrgetDetilsDetr', getDetilsDetr)

        // const getConters = getDetilsDetr.map(res => {
        //     return getCoupDetail(res.coupon_meta_id)
        // })

        // const getCoupDeteilAlls = await Promise.all(getConters).catch(err => {
        //     console.log('getCoupDeteilERR', err)
        //     return false
        // })
        if (!getCoupDeteilAlls) {
            return false
        }
        getCoupDeteilAlls.forEach(item => {
            if (!item.code) {
                getListAlls.forEach(res => {
                    if (res.coupon_meta_id === item.data.coupon_meta_id) {
                        // try {
                        //     const getJSONs = JSON.parse(item.data.type_detail)
                        //     if(getJSONs) {
                        //         res.goods_list = getJSONs.goods.map(res => res.product_id)
                        //     }
                        // } catch (error) {

                        // }
                        res.goods_list = item.data.goods.map(res => res.product_id)
                        res.goods_count = res.goods_list.length
                        // type_detail.split(',')
                        res.getDeteil = true
                    }
                })
                console.log('getListAllsgetListAllsgetListAlls', getListAlls)
            }

        })
        return true
    }
    async function getCoupDeteailList(data, list = []) {
        console.log('data0001', data)
        if (!data || !data.length) {
            return list
        }
        const aData = data.splice(0, 1)
        console.log('aData', aData)
        const getCoupDeteilAlls = aData[0].map(res => {
            return getCoupDetail(res.coupon_meta_id)
        })
        const getDaterSter = await Promise.all(getCoupDeteilAlls).catch(err => {
            console.log('getCoupDeteilERR', err)
            return false
        })
        console.log('详情结果', getDaterSter)
        list.push(...getDaterSter)
        // .then(getCoupDeteilAlls => {
        //     if (!item.code) {
        //         getListAlls.forEach(res => {
        //             if (res.coupon_meta_id === item.data.coupon_meta_id) {
        //                 res.goods_list = item.data.type_detail.split(',')
        //                 res.getDeteil = true
        //             }
        //         })
        //     }
        // })
        if (data && data.length) {
            return getCoupDeteailList(data, list)
        }
        return list
    }
}


// 检查活动信息是否满足需要创建的配置条件
const cheackGoodsComper = async (list, config, cb) => {
    // console.log('当前时间是有走到检查的')
    let stopConter = []
    // console.log('config', config)
    list = list.filter(item => {
        const getTime = config.getTime
        // console.log('getTime', getTime)
        const { start_apply_time, end_apply_time } = item
        const start = getTime[0]
        const end = getTime[1]
        return end > start_apply_time && start < end_apply_time
    })
    // console.log('list', list)
    if (config.goodsScope === 1) {
        list = list.filter(item => item.goods_count !== 0)
        if (!list || !list.length) {
            //单个任务开始 没有进行中的任务， 需要进行全部的商品设置
            // 设置需要的商品
            config.noCounpGoodList = config.getSelectGoods
            // 清空选择的商品
            addCoupTers(config, (data) => {
                data.config.getSelectGoods = data.config.getSelectGoods.filter(item => !data.config.runScususe.includes(item))


                // return
                if (data.config.getSelectGoods.length) {
                    data.isOrdouters = true
                }
                cb && cb(data)
            })
            return
        }
        // 筛选商品

        const allCoupGoods = []
        list.forEach(res => {
            allCoupGoods.push(...res.goods_list)
        })
        const noInCoupGoods = config.getSelectGoods.filter(item => !allCoupGoods.includes(item))

        if (noInCoupGoods && noInCoupGoods.length) {
            config.noCounpGoodList = noInCoupGoods
            addCoupTers(config, (data) => {
                data.config.getSelectGoods = data.config.getSelectGoods.filter(item => !data.config.runScususe.includes(item))
                if (data.config.getSelectGoods.length) {
                    data.isOrdouters = true
                }
                cb && cb(data)
            })
            return
        }
        const interCoupGoods = [] // 满足设置要求的商品
        config.getSelectGoods.forEach(item => { // 所有的活动
            list.forEach(res => { // 便利活动列表
                if (res.goods_list.includes(item)) {
                    const enterReferTime = new Date().getTime() / 1000 // (new Date().getTime() - (config.createBeforConf.sendTimeActivet || 5) * 60 * 1000) / 1000
                    const jianDateTime = res.end_apply_time - (config.createBeforConf.sendTimeActivet || 5) * 60
                    if (res.total_amount <= config.createBeforConf.sendNumActivet) {
                        config.createBeforConf.sendNumActivet = res.total_amount - 1
                    }
                    // 满足剩余数量
                    if (config.createBeforConf.createBefor === 2 && config.createBeforConf.sendNumActivet >= res.left_amount) {
                        // console.log('满足剩余数量')
                        if (!interCoupGoods.includes(item)) {
                            interCoupGoods.push(item)
                        }

                        if (!stopConter.includes(res.coupon_meta_id)) {
                            stopConter.push(res.coupon_meta_id)
                        }
                    }
                    // 满足时间
                    if (config.createBeforConf.createBefor === 1 && enterReferTime >= jianDateTime) {
                        if (!interCoupGoods.includes(item)) {
                            interCoupGoods.push(item)
                        }
                        if (!stopConter.includes(res.coupon_meta_id)) {
                            stopConter.push(res.coupon_meta_id)
                        }
                    }
                    if (config.createBeforConf.createBefor === 4 && config.createBeforConf.useNum <= res.used_amount) {
                        // console.log('满足剩余数量')
                        if (!interCoupGoods.includes(item)) {
                            interCoupGoods.push(item)
                        }

                        if (!stopConter.includes(res.coupon_meta_id)) {
                            stopConter.push(res.coupon_meta_id)
                        }
                    }
                    // 同时满足
                    if (config.createBeforConf.createBefor === 3 && (config.createBeforConf.sendNumActivet >= res.left_amount || enterReferTime >= jianDateTime || config.createBeforConf.useNum <= res.used_amount)) {
                        if (!interCoupGoods.includes(item)) {
                            interCoupGoods.push(item)
                        }
                        if (!stopConter.includes(res.coupon_meta_id)) {
                            stopConter.push(res.coupon_meta_id)
                        }
                    }
                }
            })
        })

        if (stopConter && stopConter.length) {
            // localStorage.setItem('couplistDatas', '')
            chrome.storage.local.set({
                couplistDatas: ''
            })
            const dher = await stopCoup(stopConter, config)
            setTimeout(() => {
                getCoupListFun(config, cb)
            }, 5000)
            return
        }
        cb && cb({
            code: 0,
            type: 'runTime'
        })
        return
    }
    if (config.goodsScope === 2) {
        // 全店商品
        list = list.filter(item => item.goods_count === 0)
        if (!list || !list.length) {
            addCoupTers(config, (data) => {
                cb && cb(data)
            })
            return
        }
        list.forEach(res => {
            const enterReferTime = new Date().getTime() / 1000
            const jianDateTime = res.end_apply_time - (config.createBeforConf.sendTimeActivet || 5) * 60
            if (res.total_amount <= config.createBeforConf.sendNumActivet) {
                config.createBeforConf.sendNumActivet = res.total_amount - 1
            }
            // 满足剩余数量
            if (config.createBeforConf.createBefor === 2 && config.createBeforConf.sendNumActivet >= res.left_amount) {
                stopConter.push(res.coupon_meta_id)
            }

            if (config.createBeforConf.createBefor === 4 && config.createBeforConf.useNum <= res.used_amount) {
                stopConter.push(res.coupon_meta_id)
            }
            // 满足时间
            if (config.createBeforConf.createBefor === 1 && enterReferTime >= jianDateTime) {
                stopConter.push(res.coupon_meta_id)
            }
            // 同时满足
            if (config.createBeforConf.createBefor === 3 && (config.createBeforConf.sendNumActivet >= res.left_amount || enterReferTime >= jianDateTime || config.createBeforConf.useNum <= res.used_amount)) {
                stopConter.push(res.coupon_meta_id)
            }

        })
        // return
        if (stopConter && stopConter.length) {
            // localStorage.setItem('couplistDatas', '')
            chrome.storage.local.set({
                couplistDatas: ''
            })
            // setGetIndex(0)
            const dher = await stopCoup(stopConter, config)
            setTimeout(() => {
                getCoupListFun(config, cb)
            }, 5000)
            return
        }
        cb && cb({
            code: 0,
            type: 'runTime'
        })
        return

    }

    return config
}


// 停止对应的活动 其他活动是否适用？？？？
const stopCoup = async (ids) => {
    // 获取浏览器活跃窗口
    const getouer = ids.map(res => {
        // 通知调用浏览器对应窗口创建
        return delCoup(res, { "action": 1 })
    })
    const getCoupStop = await Promise.all(getouer)
    return getCoupStop
}


const addCoupTers = async (config, cb) => {
    // 计算出时间后去做筛选
    const { noCounpGoodList, getTime, goodsScope } = config

    let start_apply_time = getTime[0] // new Date().getTime()
    let end_apply_time = getTime[1] //new Date().getTime()

    config.end_apply_time = end_apply_time
    config.start_apply_time = start_apply_time >= new Date().getTime() / 1000 ? start_apply_time : (new Date().getTime() / 1000).toFixed(0) * 1
    if (config.end_apply_time <= (new Date().getTime() / 1000)) {
        setRunStatusFun(false)
        return cb && cb({
            code: 0,
            type: 'runEndTime',
            config
        })
    }
    const getrCheackData = await cheearcjkvun(config, true)
    console.log('检查全店结果', getrCheackData)
    if (!getrCheackData.code && !getrCheackData.data?.activity_check_info?.check_pass) {
        return cb && cb({
            code: 0,
            type: 'runEndTimeGlobMax',
            config,
            msg: getrCheackData.data?.activity_check_info?.reject_reason
        })
    }
    // return
    const cheackResous = await cheearcjkvun(config)

    console.log('检查结果', cheackResous)
    // return
    config.createBeforErr = config.createBeforErr || [] // 保存的不可设置的商品， 自动跳过 返回给用户查看
    // 初始化设置的商品
    if (!cheackResous.code) {
        const datas = cheackResous.data.product_check_infos
        // console.log('datas', datas)
        if (goodsScope == 1) {
            Object.keys(datas).forEach(key => {
                if (!datas[key].check_pass) {
                    const getRodIndex = noCounpGoodList.indexOf(key.replace('_0_0', ''))
                    // console.log(getRodIndex)
                    noCounpGoodList.splice(getRodIndex, 1)
                    config.createBeforErr.push({
                        key: key.replace('_0_0', ''),
                        msg: datas[key]
                    })
                }
            })
        }
        if (goodsScope == 2) {
            console.log('全店')
        }

    } else {
        console.log('提示失败')
    }
    // 开始配置设置内容 进行设置
    const refoData = fomaterUpData(config)
    console.log('全店信息2', refoData)
    createCoupFunc(JSON.parse(JSON.stringify(refoData)), (e) => {
        // console.log('创建中', e)
        config.noCounpGoodList = []
        if (e.code == 0) {
            if (e.msgType == 'error') {
                config.createBeforErr.push(...e.errData)
            }
            if (e.msgType === 'success') {
                e.succerrData?.forEach(idunter => {
                    if (!config.runScususe.includes(idunter)) {

                        config.runScususe.push(idunter)
                    }
                })
            }
            // return
            cb && cb({
                code: 0,
                type: 'runTing',
                runData: e,
                allData: refoData,
                config
            })
        }
        if (e.code == 1) {
            config.noCounpGoodList = []
            config.createBeforErr.forEach(errKeys => {
                if (!config.runScususe.includes(errKeys.key)) {
                    config.runScususe.push(errKeys.key)
                }
            })
            cb && cb({
                code: 0,
                type: 'runEnd',
                runData: e,
                allData: refoData,
                config
            })
        }
        if (e.code == 2) {
            config.createBeforErr.forEach(errKeys => {
                if (!config.runScususe.includes(errKeys.key)) {
                    config.runScususe.push(errKeys.key)
                }
            })
            cb && cb({
                code: 0,
                type: 'runEndTime',
                runData: e,
                allData: refoData,
                config

            })
        }
    }, config)
    // 区分全店与单品优惠券



}
// 递归创建优惠券
let addCinternum = 0 // 创建次数
let maxAddNUmbuer = 30 // 最大创建次数后休息

let runStartTimeSkit = null

async function createCoupFunc(list, cb, config) {
    // console.log('list', list, config)
    const getConfigList = getLocStopConfigFun()
    if (runStartTimeSkit) {
        clearTimeout(runStartTimeSkit)
        runStartTimeSkit = null
    }
    // 在出现意外的情况下 需要重启程序
    runStartTimeSkit = setTimeout(() => {
        setRunStatusFun(false)
    }, 30000)
    if (config.end_apply_time <= (new Date().getTime() / 1000)) {
        setRunStatusFun(false)
        return cb && cb({
            code: 2,
            msg: '结束时间不能小于当前时间'
        })
    }
    const getinters = getConfigList.find(data => data.id == config.id)
    let dengterTimes = 2000
    if (addCinternum > maxAddNUmbuer) {
        dengterTimes = 12000
        addCinternum = 0
    }
    if (!getinters) {
        setRunStatusFun(false)
        return
    }
    const getSpliterEnter = list.splice(0, 1)
    console.log('getSpliterEnter', getSpliterEnter)
    if (!getSpliterEnter || !getSpliterEnter.length) {
        cb && cb({
            code: 1,
            msg: '创建成功'
        })
        setRunStatusFun(false)
        return
    }
    setRunStatusFun(true)
    let runData = {
        code: 0,
        msgType: 'success',
        msg: '',
        mterlength: list.length,
        errData: null,
        succerrData: null
    }
    createCoup(getSpliterEnter[0]).then(cretedaStautsw => {
        addCinternum++

        if (cretedaStautsw.code) {
            runData.msg = cretedaStautsw.msg
            runData.msgType = 'error'
            runData.errData = getSpliterEnter[0]?.goods.map((key) => {
                return {
                    key,
                    msg: cretedaStautsw.msg
                }
            })
        } else {
            runData.succerrData = getSpliterEnter[0]?.goods
        }
        cb && cb(runData)
        setTimeout(() => {
            createCoupFunc(list, cb, config)
        }, dengterTimes)
    }).catch(e => {
        console.log('创建失败', e)
        runData.msg = e
        runData.msgType = 'error'
        runData.errData = getSpliterEnter[0]?.goods.map((key) => {
            return {
                key,
                msg: e
            }
        })
        setTimeout(() => {
            createCoupFunc(list, cb, config)
        }, dengterTimes)
    })

}

// 检查商品是否可以设置
async function cheearcjkvun(config, globe = false) {
    // 先检查商品是否可以使用
    let getTimetype
    const { discountType, creditConf, goodsScope, end_apply_time, start_apply_time } = config

    if (discountType == 1) {
        getTimetype = {
            "activity_tool_discount_type": 1,
            "activity_tool_type": 7,

            "credit": Number((creditConf.credit * 100).toFixed(0)),

            "end_time": end_apply_time,
            "participate_type": 1,
            "start_time": start_apply_time,

            "support_type": 1,
            "validate_type": 2,



        }
    }
    if (discountType == 2) {
        getTimetype = {
            "activity_tool_discount_type": 3,
            "activity_tool_type": 7,
            "threshold": Number((creditConf.threshold * 100).toFixed(0)),
            "credit": Number((creditConf.credit * 100).toFixed(0)),

            "end_time": end_apply_time,
            "participate_type": 1,
            "start_time": start_apply_time,

            "support_type": 1,
            "validate_type": 2,
        }
    }
    if (discountType == 3) {
        getTimetype = {
            "activity_tool_discount_type": 4,
            "activity_tool_type": 7,
            "discount": Number((creditConf.discount * 10).toFixed(0)),

            "end_time": end_apply_time,
            "participate_type": 1,
            "start_time": start_apply_time,

            "support_type": 1,
            "validate_type": 2,



        }
    }
    // if (!globe) {
    //     getTimetype.support_type = 1
    //     getTimetype.participate_type = 1
    //     getTimetype.validate_type = 1
    // }
    if (goodsScope == 1 && !globe) {
        getTimetype.support_type = 1
        getTimetype.participate_type = 1
        getTimetype.validate_type = 1
        let addCkerList = []
        config.noCounpGoodList.forEach(items => {
            addCkerList.push({
                channel_id: '0',
                channel_type: 0,
                product_id: items,
            })
        })
        getTimetype.product_infos = addCkerList
    }
    // if (goodsScope == 2 && !globe) {
    //     console.log('全店优惠券的检查')
    //     getTimetype = {
    //         "validate_type": 1,
    //         "participate_type": 2,
    //         "activity_tool_type": 7,
    //         "activity_tool_discount_type": 1,
    //         "support_type": 5,
    //         "start_time": start_apply_time,
    //         "end_time": end_apply_time
    //     }
    // }
    const addPterLenth = []
    if (goodsScope !== 2 && !globe) {
        while (getTimetype.product_infos.length) {
            addPterLenth.push(getTimetype.product_infos.splice(0, 600))
        }
        const addconterdatas = addPterLenth.map(items => {
            const newDater = JSON.parse(JSON.stringify(getTimetype))
            newDater.product_infos = items
            return newDater
        })
        const getListAdd = addconterdatas.map(items => {
            return checkPromotionProductList(items)
        })
        const getConter = await Promise.all(getListAdd)
        let addChkerDater = {
            code: 0,
            data: {
                product_check_infos: {}
            }
        }
        getConter.forEach(items => {
            addChkerDater.data.product_check_infos = { ...addChkerDater.data.product_check_infos, ...items.data.product_check_infos }
        })
        return addChkerDater
    }
    const getrCheackData = await checkPromotionProductList(getTimetype)
    return getrCheackData
}

// 设置优惠券详情
function setUpDataInfo(data, updata) {
    const { total_amount, max_apply_times, discountType, creditConf, goodsScope } = data
    const { threshold, credit, discount } = creditConf
    const upDataSetInfoOns = {
        total_amount,
        max_apply_times,
        goods: null,
        discountType,
        threshold: discountType === 2 ? (threshold * 100) : null,
        credit: (discountType === 2 || discountType === 1) ? (credit * 100) : null,
        discount: discountType === 3 ? (discount * 10) : null,
        favoured_type: (() => { // 22 全店立减 42 指定立减 23全店满减 43指定满减 41指定折扣 21全店折扣 ****
            let oneNum = goodsScope === 1 ? '4' : '2'
            let towNum = discountType === 1 ? '2' : discountType === 2 ? '3' : '1'
            return `${oneNum}${towNum}` * 1
        })(),

    }

    Object.keys(upDataSetInfoOns).forEach((key) => {
        if (!upDataSetInfoOns[key]) {
            delete upDataSetInfoOns[key]
        }
    })
    return { ...updata, ...upDataSetInfoOns }
}

// 过滤创建的数据 分组
function fomaterUpData(config) {
    const { valid_period, goodsScope, couponGoodsNum, couponAfterText, noCounpGoodList } = config
    const updata = {
        "ignore": false,
        "displayChannel": 1, // 1全网公开
        period_type: 2, // 1 限制日期范围 2 限制日期天数
        goodsScope, // 1指定商品 2 全店商品
        valid_period,
        start_apply_time: config.start_apply_time, // 领取开始时间
        end_apply_time: config.end_apply_time, // 领取结束时间
        "support_type": goodsScope === 1 ? 1 : 5, // 1指定 5全店
        "jump_type": goodsScope === 1 ? 4 : 3, // 4指定商品 3全店商品
        "channel": 0,
        "from_page": "",
    }
    const quanDataListAllGood = []
    quanDataListAllGood.push(setUpDataInfo(config, updata))

    const quanDataListGoods = []
    if (goodsScope === 1) {
        const goodsShopList = []

        const selectData = JSON.parse(JSON.stringify(noCounpGoodList))
        while (selectData && selectData.length) {
            goodsShopList.push(selectData.splice(0, couponGoodsNum))
        }
        quanDataListAllGood.forEach(item => {
            goodsShopList.forEach(pit => {

                const getitem = JSON.parse(JSON.stringify(item))
                getitem.goods = pit

                quanDataListGoods.push(getitem)
            })
        })
    }
    if (goodsScope === 2) {
        quanDataListGoods.push(setUpDataInfo(config, updata))
    }
    console.log('quanDataListGoodsquanDataListGoodsquanDataListGoods', quanDataListGoods)

    quanDataListGoods.forEach((item, index) => {
        item.coupon_name = ''
        if (item.goodsScope === 1) {
            const idTypei = item.goods.length === 1 ? item.goods[0] : `${item.goods.length}个-`
            item.coupon_name = `${couponAfterText}商品A-${idTypei}-${generateRandomString(3)}`
        } else {
            item.coupon_name = `${couponAfterText}全店A-${moment().format("YYYYMMDDHHmmss")}-${generateRandomString(3)}`
        }
        item.coupon_name = item.coupon_name.slice(0, 25)
    })
    return quanDataListGoods
}

